package com.Bigbluebook.Activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.Bigbluebook.R;
import com.Bigbluebook.adapter.MyCommentAdapter;
import com.Bigbluebook.entity.Comment;
import com.Bigbluebook.ViewMode.CommentViewModel;

import java.util.List;

public class CommentActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private MyCommentAdapter myCommentAdapter;
    private CommentViewModel commentViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_comment);

        recyclerView = findViewById(R.id.myCommentsRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化 Adapter，即使没有数据
        myCommentAdapter = new MyCommentAdapter(null);
        recyclerView.setAdapter(myCommentAdapter);

        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid", -1);

        commentViewModel = new ViewModelProvider(this).get(CommentViewModel.class);
        commentViewModel.getComments(userId);
        commentViewModel.getCommentListLiveData().observe(this, new Observer<List<Comment>>() {
            @Override
            public void onChanged(List<Comment> comments) {
                // 直接在主线程上更新 Adapter
                if (myCommentAdapter != null) {
                    myCommentAdapter.updateData(comments);
                } else {
                    // 如果 Adapter 为 null，初始化它
                    myCommentAdapter = new MyCommentAdapter(comments);
                    recyclerView.setAdapter(myCommentAdapter);
                }
            }
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            WindowInsetsCompat systemBars = (WindowInsetsCompat) insets;
            Insets inset = systemBars.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(inset.left, inset.top, inset.right, inset.bottom);
            return WindowInsetsCompat.CONSUMED;
        });
    }
}